﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System.Windows.Input;
using Facebook.Schema;
using ZFCNew.Code;
using System.Linq;
using System.Collections.ObjectModel;

namespace ZFCNew.ViewModels
{
    public class FacebookSearchModel : INotifyPropertyChanged
    {
        private const string SearchApi = "https://graph.facebook.com/search?q={0}&type=post&limit=8";
        private readonly GenericSearch<FacebookSearchData> _facebookSearch;
        private string _keywords;


        public FacebookSearchModel()
        {
            _keywords = "Fifa";
            _facebookSearch = new GenericSearch<FacebookSearchData>(SearchApi);
            _facebookSearch.SearchCompleted += FacebookSearchSearchCompleted;
            FacebookHelper.GetNewsFeedCompleted += new EventHandler<SearchBaseEventArgs<Facebook.Schema.stream_data>>(FacebookHelper_GetNewsFeedCompleted);
            CurrentResult = new List<FbSearchResult>();
            GetNextResultSetCommand = new DelegateCommand(GetNextGeneralSearch, (s) => true);
            GetPreviousResultSetCommand = new DelegateCommand(GetPrevGeneralSearch, (s) => true);
            GeneralSearchCommand = new DelegateCommand(GeneralSearch, (s) => true);
            GetFriendsUpateCommand = new DelegateCommand(GetFriendsPost, (s) => true);
            GetNextFriendsUpateCommand = new DelegateCommand(GoNextFrienResult, (s) => true);
            GetPreviousFriendsUpateCommand = new DelegateCommand(GoPrevFrienResult, (s) => true);


            GeneralSearchResult = new FacebookSearchData
            {
                Data = new List<FbSearchResult>()
            };

            CurrentFriendPost= new ObservableCollection<FriendPost>();
            FacebookHelper.LoggedIn += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("IsLoggedIn"));
            FacebookHelper.LoggedOut += (s, e) => Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("IsLoggedIn"));


          
        }

        

        void FacebookSearchSearchCompleted(object sender, SearchBaseEventArgs<FacebookSearchData> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => News.Loaer.Visibility = Visibility.Collapsed);
            AdjustSearchResults(e.Results);
        }

        private const int PageSize = 4;
        private int _currentPage;

        public List<FbSearchResult> CurrentResult { get; private set; }
        public ICommand GetNextResultSetCommand { get; private set; }
        public ICommand GetPreviousResultSetCommand { get; private set; }
        public ICommand GeneralSearchCommand { get; private set; }


        public bool IsLoggedIn { get { return FacebookHelper.IsLoggedIn; } }
        public FacebookSearchData GeneralSearchResult { get; private set; }



        private void GetNextGeneralSearch(object o)
        {
            _currentPage++;
            CurrentResult = GeneralSearchResult.Data.Skip(_currentPage * PageSize).Take(PageSize).ToList();

            if (CurrentResult.Count < PageSize)
            {
                _facebookSearch.SearchDirect(GeneralSearchResult.Paging.Next);
                Deployment.Current.Dispatcher.BeginInvoke(() => News.Loaer.Visibility = Visibility.Visible);
            }
            Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("CurrentResult"));
        }

        private void GetPrevGeneralSearch(object o)
        {
            if (_currentPage > 0)
            {
                _currentPage--;
                CurrentResult = GeneralSearchResult.Data.Skip(_currentPage * PageSize).Take(PageSize).ToList();
                Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("CurrentResult"));
            }
        }

        private void AdjustSearchResults(FacebookSearchData res)
        {
            if (GeneralSearchResult.Data.Count > 200)
            {
                GeneralSearchResult.Data.Clear();
            }
            GeneralSearchResult.Data.AddRange(res.Data.Where(d => !string.IsNullOrEmpty(d.Text)));
            GeneralSearchResult.Paging = res.Paging;
            if (CurrentResult.Count < PageSize)
            {
                CurrentResult = GeneralSearchResult.Data.Skip(_currentPage * PageSize).Take(PageSize).ToList();
            }
            Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("GeneralSearchResult", "CurrentResult"));
        }

        public void GeneralSearch(object keywords)
        {
            if (keywords is string && !string.IsNullOrEmpty(keywords.ToString()))
                _keywords = keywords.ToString();
            GeneralSearchResult.Data.Clear();
            CurrentResult.Clear();
            _currentPage = 0;
            Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("GeneralSearchResult", "CurrentResult"));
            _facebookSearch.Search(_keywords);
            Deployment.Current.Dispatcher.BeginInvoke(() => News.Loaer.Visibility = Visibility.Visible);
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(params String[] info)
        {
            if (PropertyChanged != null)
            {
                foreach (var s in info)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(s));
                }

            }
        }

        #endregion

        // Friens upate
        public ObservableCollection<FriendPost> CurrentFriendPost { get; private set; }
        private List<stream_post> _friendsPost;
        public ICommand GetFriendsUpateCommand { get; private set; }
        public ICommand GetNextFriendsUpateCommand { get; private set; }
        public ICommand GetPreviousFriendsUpateCommand { get; private set; }
        private int _currentFriendPage;
        private int _totalFriendPage = 0;

        public bool CanFriendGoNext
        {
            get { return _currentFriendPage < _totalFriendPage; }
        }
        public bool CanFriendGoPrev
        {
            get { return _currentFriendPage > 0; }
        }
        
        private void GetFriendsPost(object s)
        {
            FacebookHelper.GetNewsFeed(300);
        }

        private void FacebookHelper_GetNewsFeedCompleted(object sender, SearchBaseEventArgs<stream_data> e)
        {
            _friendsPost = FilterResult(e.Results.posts.stream_post);
            _totalFriendPage = (int)Math.Ceiling(((double)_friendsPost.Count) / PageSize) - 1;
            Deployment.Current.Dispatcher.BeginInvoke(()=> NotifyPropertyChanged("FriendsPost"));
            AdjustPages();
        }

        private void GoNextFrienResult(object s)
        {
            if (CanFriendGoNext)
            {
                _currentFriendPage++;
                AdjustPages();
            }
        }

        private void GoPrevFrienResult(object s)
        {
            if (CanFriendGoPrev)
            {
                _currentFriendPage--;
                AdjustPages();
            }
        }

        private void AdjustPages()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                CurrentFriendPost.Clear();
                var newList =
                    _friendsPost.Skip(_currentFriendPage * PageSize).Take(PageSize);
                foreach (var item in newList)
                {
                    FriendPost p = new FriendPost();
                    p.stream_post = item;
                    if (FacebookHelper.Friends != null){
                        var x = FacebookHelper.Friends.FirstOrDefault(f => f.first_name == "Ramya");
                    }
                    ;
                       // FacebookHelper.Friends.FirstOrDefault(f => f.uid(f.hs_info.) == item.);
                    CurrentFriendPost.Add(p);
                }
                NotifyPropertyChanged("CanFriendGoNext", "CanFriendGoPrev");
            });
        }

        private List<stream_post> FilterResult(List<stream_post> input)
        {
            return input.Where(f=>
                f.message.ToUpper().Contains("FIFA") ||
                f.message.ToUpper().Contains("ZAKUMI") ||
                f.message.ToUpper().Contains("SOUTH AFRICA") ||
                f.message.ToUpper().Contains("WORLD CUP") ||
                f.message.ToUpper().Contains("WORLDCUP") ||
                f.message.ToUpper().Contains("WORLD-CUP") ||
                f.message.ToUpper().Contains("WORLD_CUP") ||
                f.message.ToUpper().Contains("ITALY")   ||
                f.message.ToUpper().Contains("BRAZIL")   ||
                f.message.ToUpper().Contains("ARGENTINA")||
                f.message.ToUpper().Contains("FRANCE") ||
                f.message.ToUpper().Contains("GHANA") ||
                f.message.ToUpper().Contains("USA") ||
                f.message.ToUpper().Contains("GERMANY") ||
                f.message.ToUpper().Contains("JAPAN") ||
                f.message.ToUpper().Contains("KOREA") ||
                f.message.ToUpper().Contains("DENMARK")||
                f.message.ToUpper().Contains("GOAL")

                ).ToList();
        }
    }

    public class FriendPost
    {
       public user Friend { get; set; }
       public stream_post stream_post { get; set; }
    }
}